# -*- coding: utf-8 -*-
import scrapy
import json
from toolz.curried import *

from ..items import VisitationSlot

class Spider1Spider(scrapy.Spider):
    name = 'spider1'
    allowed_domains = ['ipr.sergu.lt']

    def start_requests(self):
        scheme = "https://"
        domain = "ipr.sergu.lt"
        resource = "/api/Search"

        keyword = getattr(self, 'keyword')
        count = 200
        query = ("?"\
                + "i=10538&i=591&i=7115&i=60&i=10314&i=26&i=403&i=407&i=15&i=18&i=21&i=23&i=12&i=9955&i=43155&i=4624&i=6400&i=400"\
                +"&orderDirection=DESC"\
                +"&orderField=VisitCount"\
                +"&searchText=" + str(keyword)\
                +"&skip=0"\
                +"&take=" + str(count)
                )

        url = scheme + domain + resource + query
        req = scrapy.Request(url, callback=self.parse_doctor_search)
        reqs = [req]
        return reqs

    def parse_doctor_search(self, response):
        body = response.text
        items = json.loads(body)
        extract_doctor_id = lambda item: item['darboVietosID']
        reqs = pipe(
                items,
                map(extract_doctor_id),
                map(self.doctor_id_to_request),
                list
                )
        return reqs

    def doctor_id_to_request(self, doctor_id):
        scheme = "https://"
        domain = "ipr.sergu.lt"
        resource = "/includes/search.json.asp"

        count = 10 # 25, 50, 100, 200
        query = ("?"\
                +"PlaceID=" + str(doctor_id)\
                +"&action=LaisviLaikai"\
                +"&diena=0"\
                +"&laikas=0"\
                +"&mokama=0"\
                +"&p=0"\
                +"&r=vlaikas"\
                +"&rt=0"\
                +"&s=" + str(count)
                )

        url = scheme + domain + resource + query
        req = scrapy.Request(url, callback=self.parse_slots)
        return req

    def parse_slots(self, response):
        body = response.text
        item = json.loads(body)
        # assert( item.klaida == null )

        json_string = item['rezultatas']
        visitation_slots = json.loads(json_string)
        parsed_to_items = pipe(
                visitation_slots,
                map(self.parse_a_slot),
                list)
        return parsed_to_items

    def parse_a_slot(self, s):
        return \
        VisitationSlot(
                laikas=s['laikas'],
                komentaras=s['komentaras'],
                id=s['id'],
                kabinetas=s['kabinetas'],
                istPavadinimas=s['istPavadinimas'],
                specialybe=s['specialybe'],
                gydytojas=s['gydytojas'],
                pareigybe=s['pareigybe'],
                kabPav=s['kabPav'],
                redaguoja=s['redaguoja'],
                mokama=s['mokama']
                )

    def parse(self, response):
        # throw exception
        pass
